﻿using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Domain.AGVModels;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Domain.WCSModels;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

namespace DongFangGuoKai.WMSPlatform.Service
{
    public partial class ExternaService
    {

        /// <summary>
        /// 空箱分配储位
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="model"></param>
        /// <returns></returns>

        public bool ConveyorLineContainerFinsh(out string msg, ConveyorLineContainerModel model)
        {
            msg = string.Empty;
            bool flag = false;

            lock (_lock)
            {
                var pallnet = Context.TPallets.FirstOrDefault(t => t.PalletBarcode == model.PalletBarcode);
                if (pallnet == null)
                {
                    msg = $"{model.PalletBarcode}托盘不存在";
                    return false;
                }
                if (pallnet.Status == 0)
                {
                    msg = $"{model.PalletBarcode}托盘已禁用";
                    return false;

                }
                if (!pallnet.LocationCode.IsNullOrEmpty())
                {
                    msg = $"{model.PalletBarcode}托盘已在储位：{pallnet.LocationName}";
                    return false;

                }

                string logicPartCode = pallnet.LogicalPartCode;
                string palletBarcode = pallnet.PalletBarcode;
                //分拨仓位
                var allocateCell = Context.TCells.Where(t => t.LogicalPartCode == "DistributionArea" && t.IsLock == false && t.BusinessType == 0 && t.Status == 1 && t.FullStatus == 0 && t.ColumnNo <= 4 && t.LayerNo <= 4)
                    .OrderBy(o => o.LineNo)
                    .ThenBy(o => o.LayerNo)
                    .ThenBy(o => o.ColumnNo)
                    .FirstOrDefault();
                if (allocateCell == null)
                {
                    //"SELECT TOP 1 * from  t_Cell WHERE LogicalPartCode={0} and IsLock={1} and Status={2}  and  BusinessType={3} and FullStatus={4} ORDER BY [LineNO] ASC,[LayerNO] ASC,[ColumnNO] ASC", pallnet.LogicalPartCode, "0", "1", "0", "0"
                    List<int> ints = new List<int>()
                     {
                         8,9
                     };
                    allocateCell = Context.TCells.Where(t => ints.Contains(t.ShelfId) && t.LayerNo == 4 && t.IsLock == false && t.Status == 1 && t.BusinessType == 0 && t.FullStatus == 0)
                    .OrderBy(o => o.LineNo)
                    .ThenBy(o => o.LayerNo)
                    .ThenBy(o => o.ColumnNo)

                    .FirstOrDefault();
                }
                if (allocateCell == null)
                {
                    msg = "无可用仓位";
                    return false;
                }

                var newPallet = Context.TPallets.Where(t => t.LocationCode == allocateCell.Code).FirstOrDefault();
                if (newPallet != null)
                {
                    msg = $" {allocateCell.Name}：{newPallet.PalletName}已存在托盘";
                    return false;
                }
                using (var tran = Context.Database.BeginTransaction())
                {
                    try
                    {
                        pallnet.LocationCode = allocateCell.Code;
                        pallnet.LocationName = allocateCell.Name;
                        pallnet.ErplocationName = allocateCell.Erpcode;
                        pallnet.WarehouseId = allocateCell.WhId;
                        pallnet.WarehouseCode = allocateCell.WhCode;
                        pallnet.WarehouseName = allocateCell.WhName;
                        Context.TPallets.Update(pallnet);
                        flag = Context.SaveChanges() > 0;
                        if (!flag)
                        {
                            tran.Rollback();
                            msg = "修改托盘失败";
                            return false;
                        }
                        allocateCell.Status = 2;//锁定 
                        allocateCell.FullStatus = 0; //空箱
                        allocateCell.BusinessType = EmBusinessType.Move;  //入库  
                        Context.TCells.Update(allocateCell);
                        flag = Context.SaveChanges() > 0;
                        if (!flag)
                        {
                            tran.Rollback();
                            msg = "修改仓位失败";
                            return false;
                        }

                        Guid guid = Guid.NewGuid();
                        TInstruct instruct = new TInstruct()
                        {
                            BusinessGroupId = guid,
                            CreateUserId = 1,
                            CreateUserName = "admin",
                            Status = 2,
                            Action = EmDeviceAction.Transport,
                            WorkDeviceType = EmWorkDeviceType.AGV,
                            InstructType = EmInstructType.Move,
                            ExpectedToLocation = allocateCell.Code,//目标地址
                            FromLocation = "S00001S1502013",   //源地址
                            InstructIndex = 1,
                            PalletBarcode = palletBarcode,
                            ScanedBarcode = palletBarcode,
                            Priority = 9999,
                            FinishedQty = 0,
                            LogicalCellAddr = allocateCell.Erpcode,
                            StartTime = DateTime.Now,
                        };
                        Context.TInstructs.Add(instruct);
                        flag = Context.SaveChanges() > 0;
                        if (!flag)
                        {
                            msg = "指令保存失败";
                            tran.Rollback();
                            return false;
                        }
                        string ctnrType = "";
                        if (pallnet.Type == 1)
                        {
                            ctnrType = "2";
                        }
                        else if (pallnet.Type == 2)
                        {
                            ctnrType = "1";
                        }
                        //添加任务单
                        AddTaskModel taskModel = new AddTaskModel();

                        //生成32位uuid
                        taskModel.reqCode = guid.ToString("N");
                        taskModel.clientCode = "PDA";
                        //大料箱任务类型
                        taskModel.TaskTyp = "A13";


                        taskModel.CtnrTyp = ctnrType;
                        //生成36位uuid
                        taskModel.taskCode = guid.ToString();

                        //任务起始点仓位编码
                        taskModel.PositionCodePath = new PositionCodePathDto[2] {
                    new PositionCodePathDto() {
                        PositionCode="S00001S1502013",// 起始地址 D00080A2502013
                        Type="05"
                    },
                    new PositionCodePathDto() {
                        PositionCode=allocateCell.Erpcode,//ERP目标地址
                        Type="05"
                    }
                };
                        var res = AGVApiService.CreateTask(taskModel);
                        if (res.code == "1")
                        {
                            tran.Rollback();
                            msg = $"仓位：{allocateCell.Name} AGV调用失败：" + res.message;
                            return false;
                        }
                        msg = allocateCell.AreaName + ":" + allocateCell.Name;
                        tran.Commit();
                        return true;

                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        Logger.LogError(ex.Message);
                        msg = "异常：" + ex.Message;
                        return false;
                    }
                }

            }
        }

        public bool ConveyorLineWindowFinsh(out string msg, ConveyorLineOverModel model)
        {
            msg = string.Empty;

            string orderSn = model.OrderSn;

            var quece = _repoQueceRecard.AsQueryable()
                .Where(t => t.BillNO == orderSn && t.Status == 0)
                .OrderBy(t => t.Id)
                .First();
            if (quece == null)
            {
                msg = $"委托单：{model.OrderSn}，未找到队列信息";
                return false;
            }


            quece.Status = 1;
            quece.CounterNo = model.WindowCode;
            _repoQueceRecard
                .AsUpdateable(quece)
                .UpdateColumns("CounterNo", "Status")
                .ExecuteCommand();

            return true;
        }
    }
}
